<template>
	<!-- <view class="my-container"> -->
		<!-- Header Section -->
	<z-paging>
		<template #top>
			<view class="header">
				<view class="status-bar" :style="{ height: `${statusBarHeight}px` }"></view>
				<view class="header-content">
					<view class="header-top">
						<view class="user-profile">
							<view class="avatar-wrapper">
								<tn-avatar :url="userInfo.imgurl" size="lg">图</tn-avatar>
							</view>
							<view class="user-info">
								<text class="username">{{userInfo.staffname}}</text>
								<view class="role-badge">
									<tn-icon name="star" size="24" color="#FFD700"/>
									<text class="role-text">{{userInfo.lgnname }}</text>
								</view>
							</view>
						</view>
						<view class="action-buttons" @click="toNavigateTo">
							<view class="notification-btn" @click="toNavigateTo">
								<tn-badge :value="unEndOrderCount" type="danger">
									<tn-icon name="comment" size="56" color="#ffffff"/>
								</tn-badge>
							</view>
						</view>
					</view>
				</view>
			</view>
		</template>
		<view class="stats-section">
			<view class="stats-card">
				<view class="stat-content">
					<view class="stat-icon order-icon">
						<tn-icon name="clock" size="44" color="#36cfc9"/>
					</view>
					<view class="stat-info" @click="toNavigateTo">
						<text class="stat-value">{{unEndOrderCount}}</text>
						<text class="stat-label">待处理订单</text>
					</view>
				</view>
			</view>
			<view class="stats-card">
				<view class="stat-content">
					<view class="stat-icon invoice-icon">
						<tn-icon name="bookmark" size="44" color="#ff7a45"/>
					</view>
					<view class="stat-info">
						<text class="stat-value">{{unEndInvoiceCount}}</text>
						<text class="stat-label">待开发票</text>
					</view>
				</view>
			</view>
		</view>

		<!-- Main Content -->
		<view class="main-content">
			<!-- Order Section -->
			<view class="section order-section">
				<view class="section-header">
					<view class="title-group">
						<text class="section-title">订单管理</text>
					</view>
					<view class="header-right"  @click="clickOrderAll">
						<tn-icon name="right" size="32" color="#666"/>
					</view>
				</view>
				<view class="order-items">
					<view
						v-for="(item, index) in statusData"
						:key="index"
						class="order-item"
						@click="clickOrder(item)"
					>
						<view class="order-icon-wrapper">
							<image class="item-icon" :src="item.imgurl" mode="aspectFit"/>
						</view>
						<text class="item-text">{{item.text}}</text>
					</view>
				</view>
			</view>

			<!-- Function Grid -->
			<view class="section function-section" v-if="functionArrayData.length > 0">
				<view class="section-header">
					<view class="title-group">
						<text class="section-title">快捷功能</text>
					</view>
				</view>
				<view class="function-grid">
					<view
						v-for="(item, index) in functionArrayData.flat()"
						:key="index"
						class="function-item"
						:class="{'highlight': item.path === '/pages/invoice/invoice'}"
						@click="clickFunction(item)"
					>
						<view class="function-icon-wrapper">
							<image class="function-icon" :src="item.imgurl" mode="aspectFit"/>
							<tn-badge 
								v-if="item.path === '/pages/invoice/invoice'" 
								:value="unEndInvoiceCount" 
								type="danger"
								class="function-badge"
							/>
						</view>
						<text class="function-text">{{ item.text }}</text>
					</view>
				</view>
			</view>

			<!-- Report Section -->
			<view class="section report-section">
				<view class="section-header">
					<view class="title-group">
						<text class="section-title">数据报表</text>
					</view>
				</view>
				<view class="report-grid">
					<view
						v-for="(item, index) in reportArrayData.flat()"
						:key="index"
						class="report-item"
						@click="clickFunction(item)"
					>
						<view class="report-icon-wrapper">
							<image class="report-icon" :src="item.imgurl" mode="aspectFit"/>
						</view>
						<text class="report-text">{{ item.text }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- Footer -->
		<view class="footer">
			<tn-footer :content="appVersion" :fixed="false"/>
		</view>
	</z-paging>	 
		

		<!-- Stats Cards -->
		
	<!-- </view> -->
</template>

<script setup>
	import { ref, reactive, onMounted } from 'vue'
	import { EventBus } from '@/mitt/EventBus.js'
	import { postCall, postLoginOut } from '@/api/index.js'
	import { toastMessage } from '@/utils/toast.js'

	// Constants
	const procName = "PROC_APP_DO_MY"
	const appVersion = ref('')
	const unEndInvoiceCount = ref(0)
	const unEndOrderCount = ref(0)
	const userInfo = uni.getStorageSync('USERINFO')
	const statusBarHeight = uni.getSystemInfoSync().statusBarHeight

	// Reactive Data
	const statusData = reactive([])
	const reportData = reactive([])
	const reportArrayData = reactive([])
	const functionData = reactive([])
	const functionArrayData = reactive([])

	// Lifecycle Hooks
	onMounted(async () => {
		// 强制移除遮挡的tabbar占位符元素
		setTimeout(() => {
			try {
				// 查找并移除所有可能的tabbar占位符
				const selectors = [
					'.tn-tabbar__placeholder',
					'.tn-tabbar__placeholder.tn-u-safe-area',
					'uni-view.tn-tabbar__placeholder',
					'uni-view.tn-tabbar__placeholder.tn-u-safe-area'
				];
				
				selectors.forEach(selector => {
					const elements = document.querySelectorAll(selector);
					elements.forEach(el => {
						if (el) {
							el.style.display = 'none';
							el.style.height = '0';
							el.style.width = '0';
							el.style.zIndex = '-9999';
							el.style.pointerEvents = 'none';
							el.style.visibility = 'hidden';
							el.style.opacity = '0';
							el.style.position = 'absolute';
							el.style.top = '-999999px';
							el.style.left = '-999999px';
							console.log('已移除tabbar占位符:', selector);
						}
					});
				});
			} catch (e) {
				console.log('移除tabbar占位符时出错:', e);
			}
		}, 100);
		
		// 设置定期检查，确保遮挡元素被持续移除
		const checkInterval = setInterval(() => {
			try {
				const tabbarPlaceholder = document.querySelector('.tn-tabbar__placeholder');
				if (tabbarPlaceholder) {
					tabbarPlaceholder.style.display = 'none';
					tabbarPlaceholder.style.pointerEvents = 'none';
					console.log('持续移除tabbar占位符');
				}
			} catch (e) {
				// 忽略错误
			}
		}, 1000);
		
		// 5秒后停止检查
		setTimeout(() => {
			clearInterval(checkInterval);
		}, 5000);
		
		await initializeData()
	})

	// Initialize Data
	const initializeData = async () => {
		await Promise.all([
			getReportInfo(),
			getStateInfo(),
			getVerInfo(),
			getFunctionInfo(),
			getUnEndOrderInfo(),
			getUnEndInvoiceInfo()
		])
	}

	// Version Info
	const getVerInfo = () => {
		const systemInfo = uni.getSystemInfoSync()
		if (process.env.UNI_PLATFORM === 'app-plus' || process.env.UNI_PLATFORM === 'app') {
			appVersion.value = "版本号：" + systemInfo.appWgtVersion
		} else if (process.env.UNI_PLATFORM === 'h5') {
			appVersion.value = "版本号：" + systemInfo.appVersion
		}
	}

	// API Calls
	const getReportInfo = async () => {
		const params = {
			P_PROC_NAME: procName,
			P_ACTION: "REPORT"
		}
		const res = await postCall(params)
		if (res?.code === 200) {
			Object.assign(reportData, res.data.DATASET)
			groupArrayData(reportData, reportArrayData)
		}
	}

	const getFunctionInfo = async () => {
		const params = {
			P_PROC_NAME: procName,
			P_ACTION: "FUNCTION",
			isShowLoading: false
		}
		const res = await postCall(params)
		if (res?.code === 200) {
			Object.assign(functionData, res.data.DATASET)
			groupArrayData(functionData, functionArrayData)
		}
	}

	const getStateInfo = async () => {
		const params = {
			P_PROC_NAME: procName,
			P_ACTION: "STATE",
			isShowLoading: false
		}
		const res = await postCall(params)
		if (res?.code === 200) {
			Object.assign(statusData, res.data.DATASET)
		}
	}

	const getUnEndOrderInfo = async () => {
		const params = {
			P_PROC_NAME: "PROC_APP_DO_ORDER",
			P_ACTION: "QUERYUNEND",
			isShowLoading: false
		}
		const res = await postCall(params)
		if (res?.code === 200) {
			unEndOrderCount.value = res.data?.DATASET?.length ?? 0
		}
	}

	const getUnEndInvoiceInfo = async () => {
		const params = {
			P_PROC_NAME: "PROC_APP_DO_INVOICE",
			P_ACTION: "QUERYUNEND",
			isShowLoading: false
		}
		const res = await postCall(params)
		if (res?.code === 200) {
			unEndInvoiceCount.value = res.data?.DATASET?.length ?? 0
		}
	}

	// Helper Functions
	const groupArrayData = (sourceArray, targetArray, groupSize = 4) => {
		let currentIndex = 0
		while (currentIndex < sourceArray.length) {
			targetArray.push(sourceArray.slice(currentIndex, currentIndex + groupSize))
			currentIndex += groupSize
		}
	}

	// Navigation & Click Handlers
	const clickFunction = (item) => {
		if (item.path === "mhky") {
			handleMiniProgramLaunch()
		} else {
			uni.setStorageSync("PROC", item)
			if (item.path === "/pages/login/login") {
				loginOut()
			} else {
				uni.navigateTo({ url: item.path })
			}
		}
	}

	const handleMiniProgramLaunch = () => {
		plus.share.getServices(res => {
			const sweixin = res.find(t => t.id === 'weixin')
			if (sweixin) {
				sweixin.launchMiniProgram({
					id: 'gh_15a38a7ec8fc',
					path: 'pages/index/index',
					type: 0
				}, 
				result => {
					console.log(JSON.parse(result))
				},
				err => {
					console.log(err)
				})
			}
		})
	}

	const clickOrder = (item) => {
		uni.setStorageSync("order", item.id)
		uni.navigateTo({ url: item.path })
	}
	
	const clickOrderAll = () => {
		uni.setStorageSync("order", '0')
		uni.navigateTo({ url: '/pages/order/order' })
	}
	
	const toNavigateTo = () => {
		uni.navigateTo({ url: "/pages/order/unendorder" })
	}

	const loginOut = async () => {
		await postLoginOut()
		uni.setStorageSync("index", 0)
		uni.setStorageSync("USERINFO", "")
		uni.removeStorageSync("token")
		uni.redirectTo({ url: '/pages/login/login' })
	}
</script>

<style lang="scss" scoped>
page {
	background-color: #ffffff;
}

.my-container {
	min-height: 100vh;
	background-color: #ffffff;
	padding-bottom: env(safe-area-inset-bottom);
}

.header {
	background: var(--beginColor);
	width: 100%;
	z-index: 100;
	
	/* #ifndef MP-WEIXIN */
	padding-bottom: 30rpx;
	/* #endif */
	
	/* #ifdef MP-WEIXIN */
	padding-bottom: 40rpx;
	/* #endif */
}

.header-content {
	padding: 20rpx 40rpx;
}

.header-top {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.user-profile {
	display: flex;
	align-items: center;
	gap: 24rpx;
}

.avatar-wrapper {
	:deep(.tn-avatar) {
		width: 120rpx;
		height: 120rpx;
		border: 4rpx solid rgba(255, 255, 255, 0.2);
		box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.3);
	}
}

.user-info {
	.username {
		font-size: 36rpx;
		font-weight: 600;
		color: #ffffff;
		display: block;
		margin-bottom: 12rpx;
	}
}

.role-badge {
	display: flex;
	align-items: center;
	gap: 8rpx;
	background: rgba(255, 215, 0, 0.15);
	padding: 6rpx 16rpx;
	border-radius: 30rpx;
	
	.role-text {
		font-size: 24rpx;
		color: #FFD700;
	}
}

.notification-btn {
	background: rgba(255, 255, 255, 0.1);
	padding: 16rpx;
	border-radius: 20rpx;
	
	:deep(.tn-badge) {
		.tn-badge__content {
			background: #ff4d4f;
			border: none;
			padding: 6rpx 12rpx;
			font-size: 22rpx;
			border-radius: 20rpx;
		}
	}
}

.stats-section {
	padding: 30rpx;
	display: flex;
	gap: 30rpx;
	background-color: #ffffff;
}

.stats-card {
	flex: 1;
	background: #ffffff;
	border-radius: 24rpx;
	padding: 30rpx;
	box-shadow: 0 10rpx 40rpx rgba(0, 0, 0, 0.12);
}

.stat-content {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.stat-icon {
	padding: 20rpx;
	border-radius: 20rpx;
	
	&.order-icon {
		background: rgba(54, 207, 201, 0.1);
	}
	
	&.invoice-icon {
		background: rgba(255, 122, 69, 0.1);
	}
}

.stat-info {
	.stat-value {
		font-size: 40rpx;
		font-weight: 600;
		color: #333;
		display: block;
	}
	
	.stat-label {
		font-size: 24rpx;
		color: #999;
		margin-top: 4rpx;
	}
}

.main-content {
	padding: 0 30rpx;
	background-color: #ffffff;
}

.section {
	background: #ffffff;
	border-radius: 24rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 10rpx 40rpx rgba(0, 0, 0, 0.12);
}

.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 30rpx;
}

.title-group {
	.section-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
		display: block;
	}
	
	.section-subtitle {
		font-size: 22rpx;
		color: #999;
		margin-top: 4rpx;
	}
}

.order-items {
	display: grid;
	grid-template-columns: repeat(5, 1fr);
	gap: 20rpx;
	width: 100%;
}

.order-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 12rpx;
}

.order-icon-wrapper {
	background: #f8f9fa;
	padding: 0;
	border-radius: 16rpx;
	transition: all 0.3s ease;
	width: 100rpx;
	height: 100rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.1);
	
	&:active {
		transform: scale(0.95);
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.08);
	}
	
	.item-icon {
		width: 100rpx;
		height: 100rpx;
	}
}

.item-text {
	font-size: 24rpx;
	color: #666;
	text-align: center;
	width: 100%;
	white-space: normal;
	line-height: 1.4;
}

.function-grid, .report-grid {
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 20rpx;
}

.function-item, .report-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 12rpx;
	padding: 20rpx;
	border-radius: 16rpx;
	transition: all 0.3s ease;
	
	&:active {
		transform: scale(0.95);
	}
}

.function-item.highlight {
	background: rgba(var(--beginColor-rgb), 0.1);
}

.function-icon-wrapper, .report-icon-wrapper {
	position: relative;
	background: #f8f9fa;
	padding: 0;
	border-radius: 16rpx;
	box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.1);
	width: 100rpx;
	height: 100rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	
	&:active {
		transform: scale(0.95);
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.08);
	}
	
	.function-icon, .report-icon {
		width: 100rpx;
		height: 100rpx;
	}
}

.function-badge {
	position: absolute;
	top: -10rpx;
	right: -10rpx;
}

.function-text, .report-text {
	font-size: 24rpx;
	color: #666;
	text-align: center;
}

.footer {
	padding: 30rpx;
	font-size: 24rpx;
	text-align: center;
	margin-bottom:  5vh ;
	background-color: #fefefe
}

:deep(.tn-badge) {
	.tn-badge__content {
		transform: translate(50%, -50%);
		min-width: 32rpx;
		height: 32rpx;
		padding: 0 10rpx;
		font-size: 22rpx;
		line-height: 32rpx;
		border-radius: 16rpx;
	}
}

:deep(.z-paging) {
	.z-paging-content {
		background-color: #ffffff;
	}
}
</style>

